/* SPDX-License-Identifier: MIT */

package com.light.theme;

import atlantafx.base.theme.Theme;
import com.light.layout.ModalDialog;
import com.light.thread.FxAsyncTask;
import com.light.util.FxApplicationContextUtils;
import com.light.util.H2PoolUtils;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;

import java.util.Objects;

import static com.light.util.FxApplicationContextUtils.THEME_LIST;

/**
 * 主题对话框
 */
public final class ThemeDialog extends ModalDialog {

    private final TilePane thumbnailsPane = new TilePane(20, 20);
    private final ToggleGroup thumbnailsGroup = new ToggleGroup();

    public ThemeDialog() {
        super();

        header.setTitle("选择主题");
        content.setBody(createContent());
        content.setFooter(null);

        updateThumbnails();

        thumbnailsGroup.selectedToggleProperty().addListener((obs, old, val) -> {
            if (val != null && val.getUserData() instanceof Theme theme) {
                FxApplicationContextUtils.CURRENT_THEME_NAME.set(theme.getName());
                Application.setUserAgentStylesheet(theme.getUserAgentStylesheet());
                FxAsyncTask.runOnce("主题更新同步数据库", () -> H2PoolUtils.updateDictData("GIT_CURRENT_THEME", theme.getName()));
            }
        });
    }

    private VBox createContent() {
        thumbnailsPane.setAlignment(Pos.TOP_CENTER);
        thumbnailsPane.setPrefColumns(3);
        thumbnailsPane.setStyle("-color-thumbnail-border:-color-border-subtle;");
        var root = new VBox(thumbnailsPane);
        root.setPadding(new Insets(20));
        return root;
    }

    private void updateThumbnails() {
        thumbnailsPane.getChildren().clear();
        THEME_LIST.forEach(theme -> {
            var thumbnail = new ThemeThumbnail(theme);
            thumbnail.setToggleGroup(thumbnailsGroup);
            thumbnail.setUserData(theme);
            thumbnail.setSelected(Objects.equals(
                    FxApplicationContextUtils.CURRENT_THEME_NAME.get(),
                    theme.getName()
            ));
            thumbnailsPane.getChildren().add(thumbnail);
        });
    }
}
